<script>
export default {
  name: "AiLogin",
  data(){
    return {

    }
  },
  methods:{
    openx(){
      let video = this.$refs.videoRef;
      let constraints = {
        video: {            //这里是摄像头的信息
          height: 500,
          width: 500
        }
      }
      let isok = navigator.mediaDevices.getUserMedia(constraints); //这里主要是用于请求用户打开摄像头的权限
      isok.then(res => {     //可以看出是使用promise封装的 那么我们就可以使用then和catch
        video.srcObject = res;    //用户允许时 将摄像头对象的画面转移到video上面
        video.play();                //打开video的画面
      }).catch((err) => {
        console.log(err)            //拒绝时打印错误信息
      })
    },
    AiLogin(){
      // canvas.style.display = "none";
      let canvas = this.$refs.videoCanvas;
      canvas.getContext("2d").drawImage(this.$refs.videoRef, 0, 0, 500, 500);   //第一个参数为要截取的dom对象，第二个和第三个为xy轴的偏移值    3-4为截取图像的大小
      var imgurl = canvas.toDataURL("image/jpg");
      // var img1 = document.getElementById("img1");
      // img1.src = imgurl;  //此处为base64格式的图片
      // console.log(imgurl);
      //两种上传方式，任选一种，推荐上传base64格式图片
      this.form_upload(imgurl,"file");

    },
    form_upload(imgurl,filename){

      var index = imgurl.indexOf("base64,");
      var img_base64 = imgurl.substring(index+7);
      let bytes = window.atob(img_base64);
      let ab = new ArrayBuffer(bytes.length);
      let ia = new Uint8Array(ab);
      for (let i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i)
      }
      let imgs = new File([ab], "oldname.png", { type: 'image/jpg' });
      const formData = new FormData();
      formData.append(filename, imgs);
      this.$http({url:"/user/ailogin",data:formData,method:"post"}).then(res=>{
        if(res.data.code==200) {
          //登陆成功,token字符串
          window.sessionStorage.setItem("token",res.data.data)
          this.$refs.videoRef.srcObject.getTracks()[0].stop()//关闭摄像头
          //页面跳转、路由
          this.$router.push("/home");
        }else{
          //登录失败
          this.$message.error("登录失败，请重新登录");
          this.openx();
        }
      })
    }
  },
  mounted() {
    this.openx();
  }

}
</script>

<template>
  <div class="allDiv">
    <video ref="videoRef" width="500" height="500" autoplay class="video" style="border-radius: 50% 50%"></video>
    <canvas ref="videoCanvas" id="canvas" width="500" height="500" style="display: none"></canvas>
    <el-button type="success" @click="AiLogin">登录</el-button>
  </div>

</template>

<style scoped>
.allDiv{
  height: 100%;
  width: 100%;
  background-color: #2c3e50;
}
</style>
